#include "net_pan.h"
int exitPipe[2];
void handler(int signum){
    printf("signum = %d\n", signum);
    write(exitPipe[1],"1",1);
}
int argv_get(const char *path, char *p_ip, char *p_port_number, char *p_num);
int main(int argc, char **argv){
    // ./server 192.168.121.128 1234 3
    char* arg_s[4];
    for(int i=0;i<4;i++)arg_s[i]=(char*)calloc(1024,sizeof(char));
    char a[1024]="../conf/server.conf";
    argv_get(a,arg_s[1],arg_s[2],arg_s[3]);
    pipe(exitPipe);
    if(fork() != 0){ //父进程的故事
        printf("pid = %d\n", getpid());
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        exit(0);
    }
    //子进程额外需要监听exitPipe的读端
    close(exitPipe[1]);
    // 准备线程池的数据结构
    net_pan_t net_pan;
    int workernum = atoi(arg_s[3]);
    net_pan_init(&net_pan,workernum);
    // 创建子线程
    makeWorker(&net_pan);
    int sockfd;//初始化tcp连接
    tcpInit(arg_s[1],arg_s[2],&sockfd);
    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);//监听sockfd
    epollAdd(epfd,exitPipe[0]);
    int ret=mkdir("./client_dir",0777);//创建server下的client_dir目录存放用户的文件
    struct epoll_event readyset[2];
    while(1){
        int readynum = epoll_wait(epfd,readyset,2,-1);
        for(int i = 0; i < readynum; ++i){
            if(readyset[i].data.fd == sockfd){
                struct sockaddr_in saddr;
                socklen_t len=sizeof(saddr);
                int netfd = accept(sockfd,(struct sockaddr*)&saddr,&len);//增加IP和PORT
                //将客户端连接时间记录到日志中
                SYSLOG("One client","CONNECT","NULL","success");
                pthread_mutex_lock(&net_pan.taskQueue.mutex);
                taskEnQueue(&net_pan.taskQueue, netfd,&saddr);
                printf("main thread send a task!\n");
                pthread_cond_signal(&net_pan.taskQueue.cond);
                pthread_mutex_unlock(&net_pan.taskQueue.mutex);
            }
            else if(readyset[i].data.fd == exitPipe[0]){
                printf("net_pan is going to exit!\n");
                pthread_mutex_lock(&net_pan.taskQueue.mutex);
                net_pan.exitFlag = 1;//修改标志，表示将要退出
                pthread_cond_broadcast(&net_pan.taskQueue.cond);
                pthread_mutex_unlock(&net_pan.taskQueue.mutex);
                for(int j = 0; j < workernum; ++j){
                    pthread_join(net_pan.tidArr[j],NULL);
                }
                printf("main thread is closing!\n");
                exit(0);
            }
        }
    }
}
int argv_get(const char *path, char *p_ip, char *p_port_number, char *p_num) {
    int fd = open(path, O_RDWR);
    if(fd == -1) {
        return -1;
    }

    char buf[1024] = {0};
    read(fd, &buf, sizeof(buf));
    for (int i = 0; i < 15; ++i) {
        p_ip[i] = buf[i];
    }

    int j = 0;
    for (int i = 16; i < 20; ++i) {
        p_port_number[j] = buf[i];
        ++j;
    }

    p_num[0] = buf[21];
    return 0;
}

